package com.qf.lisetener;

import com.qf.entity.Email;
import com.rabbitmq.client.Channel;
import jdk.nashorn.internal.ir.CallNode;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.concurrent.*;

@Component
@Slf4j
public class EmailQueueListener {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;

    // 创建一个线程池
    ExecutorService executorService = Executors.newFixedThreadPool(10);

    @RabbitListener(queues = "${email.emailQueueName}")
    public void sendEmail(Email email, Channel channel, Message message) throws MessagingException {


        executorService.submit(new Runnable() {
            @SneakyThrows
            @Override
            public void run() {

                log.debug("监听器接收到邮件对象:" + email);
                // 1.发送邮件
                MimeMessage mimeMessage = javaMailSender.createMimeMessage();

                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage);

                helper.setSubject(email.getTitle());// 设置标题
                helper.setText(email.getContent(), true); // 内容
                helper.setTo(email.getTo()); // 收件人
                String[] cc = email.getCc();
                if (cc != null && cc.length > 0) {
                    helper.setCc(cc);
                }
                helper.setFrom(username); // 设置发件人

                javaMailSender.send(mimeMessage);
                log.debug("邮件发送成功。。。:" + email);
                try {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }
}
